package com.haixee.parkdemo.auth.service.impl;

import com.haixee.parkdemo.auth.dao.RoleCustomMapper;
import com.haixee.parkdemo.auth.dao.RoleMapper;
import com.haixee.parkdemo.auth.entity.dto.RoleDTO;
import com.haixee.parkdemo.auth.enums.RoleScope;
import com.haixee.parkdemo.auth.model.Role;
import com.haixee.parkdemo.auth.service.RoleScopeService;
import com.haixee.parkdemo.auth.service.RoleService;
import com.haixee.parkdemo.common.context.WebContextHolder;
import com.haixee.parkdemo.common.exception.BusinessException;
import com.haixee.parkdemo.common.response.CommonResEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleCustomMapper roleCustomMapper;

    @Autowired
    private RoleScopeService roleScopeService;

    @Override
    @Transactional
    public void addRole(String name, Integer tenantId) {

        Role role = new Role();
        role.setName(name);

        if (WebContextHolder.getAuth().getTenantId() == 0) {
            role.setTenantId(tenantId);
        } else {
            if (tenantId != null) {
                throw new BusinessException(CommonResEnum.BAD_REQUEST);
            }
            role.setTenantId(tenantId);
        }

        roleMapper.insertSelective(role);

        roleScopeService.insertRoleScope(role.getId(), RoleScope.ALL.getScope());

    }

    @Override
    public List<RoleDTO> selectAll(Integer tenantId) {
        return roleCustomMapper.selectAll(tenantId);
    }

    @Override
    public List<Integer> getAclList(Integer roleId) {
        return roleCustomMapper.selectAclIdByRoleId(roleId);
    }

    @Override
    @Transactional
    public void setAcl(Integer roleId, List<Integer> aclList) {
        roleCustomMapper.deleteByRoleId(roleId);
        if (aclList != null && aclList.size() != 0) {
            roleCustomMapper.insertRoleAclList(roleId,aclList);
        }
    }


}
